package org.zqh.webserver;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
/**
 * 针对客户端的请求，新启动一个线程，处理客户请求的文件
*    
* 项目名称：zqhapache   
* 类名称：Processor   
* 类描述：   
* 创建人：zhangqh   
* 创建时间：2015年5月24日 上午1:11:58   
* 修改人：zhangqh  
* 修改时间：2015年5月24日 上午1:11:58   
* 修改备注：   
* @version    
*
 */
public class Processor extends Thread {
	Socket socket = null;
	InputStream in = null;
	PrintStream out = null;

	public Processor(Socket socket) {
		this.socket = socket;
		try {
			in = socket.getInputStream();
			out = new PrintStream(socket.getOutputStream());
			// String a = parse(in);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void run() {

		outputFileContent(parse(in));

	}

	public String parse(InputStream in) {
		BufferedReader br = new BufferedReader(new InputStreamReader(in));
		String fileName = "";
		try {
			String str = br.readLine();
			String[] s = str.split(" ");
			if (s.length != 3) {
				sendErrMessage(400, "Client query error!");
				return null;
			}
			System.out.println("code=" + s[0] + " filename=" + s[1] + " http version=" + s[2]);
			fileName = s[1];
		} catch (IOException e) {
			e.printStackTrace();
		}

		return fileName;
	}

	public void sendErrMessage(int errorCode, String errorMessage) {
		out.println("HTTP/1.0 " + errorCode + " " + errorMessage);
		out.println("content-type:text/html");
		out.println();
		out.println("<html><head><title>Error Message");
		out.println("</title>");
		out.println("<body>");
		out.println("<h1>ErrorCode=" + errorCode + " ErrMessage=" + errorMessage + "</h1>");
		out.println("</body>");
		out.println("</html>");
		out.flush();
		out.close();
	}

	public void outputFileContent(String fileName) {
		File f = new File("d:\\" + fileName);
		try {
			InputStream in = new FileInputStream(f);
			byte b[] = new byte[(int) f.length()];
			in.read(b);
			out.println("HTTP/1.0 200 file");
			out.println("content-length:" + b.length);
			out.println();
			out.write(b);
			out.flush();
			out.close();
			in.close();

		} catch (FileNotFoundException e) {
			sendErrMessage(404, "file not found");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
